package com.xiong.wuliao.homefragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.xiong.wuliao.R;
import com.xiong.wuliao.SpecialActivity;
import com.xiong.wuliao.adapter.MyHomeListAdapter;
import com.xiong.wuliao.entity.HomeStorys;
import com.xiong.wuliao.entity.Urls;
import com.xiong.wuliao.interfaces.OnLoveClickListener;
import com.xiong.wuliao.util.HomeJSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 爱电影Fragment
 */
public class DianyingFragment extends Fragment implements OnLoveClickListener {
	private SwipeRefreshLayout mySwipeRefreshLayoutDianYing;
	private ListView myListViewDianYing;

	// 刷新后请求服务器的参数
	private int offset = 0;
	// 是否到达页面底部的标注
	private boolean isBottom = false;
	// 保存服务器传过来的数据
	private List<HomeStorys> storysList = new ArrayList<>();
	// ListView的自定义适配器
	private MyHomeListAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_dianying, container, false);
		findView(view);
		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();
		setMyAdapter();
		setListener();
	}

	/**
	 * 设置监听
	 */
	private void setListener() {
		/**
		 * 上拉加载的监听
		 */
		myListViewDianYing.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (isBottom && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
					offset += 20;
					getDianYingServerData();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				isBottom = firstVisibleItem + visibleItemCount == totalItemCount;
			}
		});

		/**
		 * 下拉刷新的监听
		 */
		mySwipeRefreshLayoutDianYing.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			@Override
			public void onRefresh() {
				offset += 20;
				getDianYingServerData();
			}
		});

		/**
		 * ListView的item点击事件
		 */
		myListViewDianYing.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				HomeStorys storys = storysList.get(position);
				String lastId = storys.getId();
				Intent intent = new Intent(getActivity(), SpecialActivity.class);
				intent.putExtra("lastId", lastId);
				startActivity(intent);
			}
		});
	}

	/**
	 * 设置适配器
	 */
	private void setMyAdapter() {
		adapter = new MyHomeListAdapter(getActivity(), storysList);
		myListViewDianYing.setAdapter(adapter);
		// 设置接口
		adapter.setLoveListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		getDianYingServerData();
	}

	/**
	 * 保存服务器数据
	 */
	private void getDianYingServerData() {
		OkHttpUtils.get(Urls.DianYingPath)
				.params("gender", 2)
				.params("limit", 20)
				.params("offset", offset)
				.params("generation", 2)
				.execute(new StringCallback() {
					@Override
					public void onSuccess(String s, Call call, Response response) {
						JSONObject jsonObject = null;
						try {
							jsonObject = new JSONObject(s.trim());
							String result = jsonObject.getString("message");
							if (result.equals("OK")) {

								storysList.addAll(HomeJSON.saveHomeStory(s.trim()));
								adapter.notifyDataSetChanged();
								mySwipeRefreshLayoutDianYing.setRefreshing(false);
							} else {
								Toast.makeText(getActivity(), "数据请求失败", Toast.LENGTH_SHORT).show();
								mySwipeRefreshLayoutDianYing.setRefreshing(false);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	/**
	 * 初始化控件
	 *
	 * @param view
	 */
	private void findView(View view) {
		mySwipeRefreshLayoutDianYing = (SwipeRefreshLayout) view.findViewById(R.id.mySwipeRefreshLayoutDianYing);
		myListViewDianYing = (ListView) view.findViewById(R.id.myListViewDianYing);
	}

	/**
	 * 点赞接口回调
	 * @param view
	 */
	@Override
	public void loveClick(View view) {
		final int position = (int) view.getTag();
		if (storysList.get(position).isLiked()) {
			Toast.makeText(getActivity(), "已经收藏了", Toast.LENGTH_SHORT).show();
		} else {
			SharedPreferences prefe = getActivity().getSharedPreferences("kkUser", getActivity().MODE_PRIVATE);
			String uid = "";
			uid = prefe.getString("id", "");
			if (uid.equals("")) {
				Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
			} else {
				OkHttpUtils.get(Urls.LovePath)
						.params("uid", uid)
						.params("aid", storysList.get(position).getId())
						.execute(new StringCallback() {
							@Override
							public void onSuccess(String s, Call call, Response response) {
								JSONObject jsonObject = null;
								try {
									jsonObject = new JSONObject(s.trim());
									String result = jsonObject.getString("message");
									if (result.equals("OK")) {
										storysList.get(position).setLiked(true);
										adapter.notifyDataSetChanged();
									} else {
										Toast.makeText(getActivity(), "点赞失败", Toast.LENGTH_SHORT).show();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void onError(Call call, Response response, Exception e) {
								super.onError(call, response, e);
								Toast.makeText(getActivity(), "点赞1失败", Toast.LENGTH_SHORT).show();
							}
						});
			}
		}
	}
}
